package com.example.demo.demos.gui;

import com.example.demo.demos.entity.SendMail;
import com.example.demo.demos.entity.UploadList;
import com.example.demo.demos.repository.SendMailRepository;
import com.example.demo.demos.repository.UploadListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Component
public class Page2Panel extends JPanel {
    private JTable table;
    private JScrollPane scrollPane;
    private JTextField searchField;
    private JButton searchButton;
    private JComboBox<String> pageSizeComboBox;
    private JLabel currentPageLabel;
    private JLabel totalPagesLabel;
    private JButton prevButton;
    private JButton nextButton;
    private JButton[] pageButtons = new JButton[3]; // 最近三页
    private int currentPage = 0;
    private int pageSize = 10;
    private int totalPages = 0;
    private static final int DUPLICATE_FILE_COLUMN_INDEX = 8; // 去重记录文件列索引

    @Autowired
    private SendMailRepository sendMailRepository;

    @Autowired
    private UploadListRepository uploadListRepository;

    public Page2Panel() {
        setLayout(new BorderLayout());

        // 搜索区域
        JPanel searchPanel = new JPanel();
        searchField = new JTextField(20);
        searchButton = new JButton("搜索");
        searchPanel.add(new JLabel("搜索:"));
        searchPanel.add(searchField);
        searchPanel.add(searchButton);

        // 分页控件
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JLabel pageSizeLabel = new JLabel("每页:");
        pageSizeComboBox = new JComboBox<>(new String[]{"10", "20", "50", "100"});
        currentPageLabel = new JLabel("第 1 页");
        totalPagesLabel = new JLabel("共 0 页");

        // 初始化页码按钮
        for (int i = 0; i < 3; i++) {
            pageButtons[i] = new JButton();
            pageButtons[i].addActionListener(e -> {
                int pageNum = Integer.parseInt(((JButton) e.getSource()).getText());
                currentPage = pageNum - 1;
                loadPage(currentPage);
            });
            paginationPanel.add(pageButtons[i]);
        }

        // 上一页/下一页按钮
        prevButton = new JButton("上一页");
        nextButton = new JButton("下一页");

        // 添加到面板
        paginationPanel.add(pageSizeLabel);
        paginationPanel.add(pageSizeComboBox);
        paginationPanel.add(currentPageLabel);
        paginationPanel.add(totalPagesLabel);
        paginationPanel.add(prevButton);
        paginationPanel.add(nextButton);

        // 表格
        table = new JTable();
        // 设置表格内容居中对齐的渲染器
        setupTableRenderer();
        // 添加表格鼠标监听器，用于打开文件
        setupTableMouseListener();
        scrollPane = new JScrollPane(table);

        add(searchPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(paginationPanel, BorderLayout.SOUTH);

        // 搜索事件
        searchButton.addActionListener(e -> {
            currentPage = 0;
            loadPage(currentPage);
        });

        // 每页数量变化
        pageSizeComboBox.addActionListener(e -> {
            pageSize = Integer.parseInt((String) pageSizeComboBox.getSelectedItem());
            currentPage = 0;
            loadPage(currentPage);
        });

        // 上一页
        prevButton.addActionListener(e -> {
            if (currentPage > 0) {
                currentPage--;
                loadPage(currentPage);
            }
        });

        // 下一页
        nextButton.addActionListener(e -> {
            if (currentPage < totalPages - 1) {
                currentPage++;
                loadPage(currentPage);
            }
        });
    }

    // 设置表格单元格渲染器，使内容居中对齐
    private void setupTableRenderer() {
        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, centerRenderer);
    }

    // 设置表格鼠标监听器，处理文件打开
    private void setupTableMouseListener() {
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                // 获取点击的行和列
                int viewRow = table.rowAtPoint(evt.getPoint());
                int viewCol = table.columnAtPoint(evt.getPoint());

                // 检查是否点击了"去重记录文件"列
                if (viewCol == DUPLICATE_FILE_COLUMN_INDEX && viewRow != -1) {
                    // 转换为模型索引，处理排序/过滤的情况
                    int modelRow = table.convertRowIndexToModel(viewRow);
                    int modelCol = table.convertColumnIndexToModel(viewCol);

                    // 获取文件路径
                    String filePath = (String) table.getModel().getValueAt(modelRow, modelCol);

                    // 打开文件
                    if (filePath != null && !filePath.trim().isEmpty()) {
                        openFile(filePath.trim());
                    } else {
                        JOptionPane.showMessageDialog(Page2Panel.this,
                                "文件已被清理", "提示", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }
        });
    }

    // 打开文件的方法
    private void openFile(String filePath) {
        // 验证文件是否存在
        File file = new File(filePath);
        if (!file.exists()) {
            JOptionPane.showMessageDialog(this,
                    "文件不存在: " + filePath, "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        try {
            // 根据操作系统类型选择合适的命令
            String os = System.getProperty("os.name").toLowerCase();
            ProcessBuilder pb;

            if (os.contains("win")) {
                // Windows系统
                pb = new ProcessBuilder("cmd", "/c", "start", "\"\"", filePath);
            } else if (os.contains("mac")) {
                // macOS系统
                pb = new ProcessBuilder("open", filePath);
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux系统
                pb = new ProcessBuilder("xdg-open", filePath);
            } else {
                JOptionPane.showMessageDialog(this,
                        "不支持的操作系统", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 启动进程打开文件
            pb.start();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this,
                    "打开文件失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }

    public void loadPage(int page) {
        String search = searchField.getText();
        List<SendMail> data = fetchDataFromServer(search, page);
        updateTable(data);
        updatePaginationUI();
    }

    private List<SendMail> fetchDataFromServer(String search, int page) {
        return sendMailRepository.findByMsgContainingOrderByIdDesc(search, PageRequest.of(page, pageSize)).getContent();
    }

    private void updateTable(List<SendMail> data) {
        String[] columns = {"ID", "邮箱", "文件地址", "发送时间", "执行时间","发送状态", "发送结果", "发送次数","去重记录文件"};
        Object[][] rows = new Object[data.size()][9];
        List<Integer> uidArr = data.stream().map(t->t.getUid()).collect(Collectors.toList());
        Page<UploadList> uploadListPage = uploadListRepository.findByIdIn(uidArr, Pageable.ofSize(1000));
        List<UploadList> lists = uploadListPage.getContent();
        for (int i = 0; i < data.size(); i++) {
            SendMail entity = data.get(i);
            AtomicReference<UploadList> singleOne = new AtomicReference<>(new UploadList());
            lists.stream().filter(t->t.getId().equals(entity.getUid())).findFirst().ifPresent(p->{
                singleOne.set(p);
            });
            rows[i][0] = entity.getId();
            rows[i][1] = singleOne.get().getEmail();
            rows[i][2] = singleOne.get().getFileName();
            rows[i][3] = entity.getCreatedAt();
            rows[i][4] = entity.getExTime();
            rows[i][5] = entity.getSendStatus().equals(0) ? "失败" : "成功";
            rows[i][6] = entity.getMsg();
            rows[i][7] = String.valueOf(entity.getSendCount());
            rows[i][8] = entity.getOriginFile();
        }
        table.setModel(new DefaultTableModel(rows, columns));
    }

    private void updatePaginationUI() {
        // 获取总页数
        String search = searchField.getText();
        totalPages = sendMailRepository.findByMsgContainingOrderByIdDesc(search, PageRequest.of(0, pageSize)).getTotalPages();

        currentPageLabel.setText("第 " + (currentPage + 1) + " 页");
        totalPagesLabel.setText("共 " + totalPages + " 页");

        // 更新页码按钮
        for (int i = 0; i < 3; i++) {
            int pageNum = currentPage - 1 + i;
            if (pageNum >= 0 && pageNum < totalPages) {
                pageButtons[i].setText(String.valueOf(pageNum + 1));
                pageButtons[i].setVisible(true);
            } else {
                pageButtons[i].setVisible(false);
            }
        }
    }
}
